package thread.alternate_print;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-08-01 22:02
 **/
public class AlternatePrint {

    private final int threadCount;
    private final int MAX = 100;
    private int count = 1;
    private final ReentrantLock lock = new ReentrantLock(true);
    private final Condition[] conditions;

    public AlternatePrint(int threadCount) {
        this.threadCount = threadCount;
        // 初始化condition
        conditions = new Condition[threadCount];
        for (int i = 0; i < threadCount; i++) {
            conditions[i] = lock.newCondition();
        }
    }

    public void print(int threadIndex) {
        // 每个线程一直尝试获取锁,直到不满足条件为止
        while (true) {
            try {
                lock.lock();
                // 1. 如果不该我做事
                while ((count - 1) % threadCount != threadIndex) {
                    conditions[threadIndex].await();
                    // 之前判断是不是已经做完了
                    if (count > MAX) {
                        signalNext(threadIndex);
                        return;
                    }
                }

                // 2. 该我做事，
                // 之前判断是不是已经做完了
                if (count > MAX) {
                    signalNext(threadIndex);
                    return;
                }

                System.out.println(Thread.currentThread().getName() + "-" + count++);
                signalNext(threadIndex);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            } finally {
                lock.unlock();
            }
        }
    }

    private void signalNext(int threadIndex) {
        int nextIndex = (threadIndex + 1) % threadCount;
        conditions[nextIndex].signal();
    }

    public static void main(String[] args) {
        int threadCount = 3;
        AlternatePrint printer = new AlternatePrint(threadCount);
        for (int i = 0; i < threadCount; i++) {
            final int threadIndex = i;
            new Thread(() -> printer.print(threadIndex), "t" + (i + 1)).start();
        }
    }


}
